// 引入编辑器样式
import 'braft-editor/dist/index.css';
import 'braft-extensions/dist/code-highlighter.css';
// @ts-ignore
import CodeHighlighter from 'braft-extensions/dist/code-highlighter';
import React from 'react';
// 引入编辑器组件
import BraftEditor from 'braft-editor';
import {Button, Card, Divider, Modal, Form, Switch, Select, Steps, Input, Row, Col, message} from 'antd';
import { EyeOutlined, ArrowLeftOutlined } from '@ant-design/icons';
import { Link } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import { save } from "@/services/article";

BraftEditor.use(
  CodeHighlighter({
    includeEditors: ['editor-with-code-highlighter'],
  }),
);

const { Step } = Steps;

export default class Article extends React.Component {

  private modalData = {
    title: '',
    content: '',
    categoryId: '',
    readNum: 0,
    likeNum: 0,
    formFlag: '0'
  }


  state = {
    // 创建一个空的editorState作为初始值
    modalVisible: false,
    modalLoading: false,
    editorState: BraftEditor.createEditorState(null),
  };

  async componentDidMount() {
    // 假设此处从服务端获取html格式的编辑器内容
    // const htmlContent = await fetchEditorContent()
    // 使用BraftEditor.createEditorState将html字符串转换为编辑器需要的editorStat
    // this.setState({
    //   editorState: BraftEditor.createEditorState(htmlContent)
    // })
  }

  submitContent = () => {
    // 在编辑器获得焦点时按下ctrl+s会执行此方法
    // 编辑器内容提交到服务端之前，可直接调用editorState.toHTML()来获取HTML格式的内容
    const htmlContent = this.state.editorState.toHTML();
    this.modalData.content = htmlContent;
    // const result = await saveEditorContent(htmlContent)
  };

  handlePublish = () => {
    // 打开窗口
    this.setState({ modalVisible: true });
  };

  handleOk = () => {
    if (this.modalData.title === '' || this.modalData.title === null) {
      message.error("请输入 文章标题！");
    } else if (this.modalData.categoryId === '' || this.modalData.categoryId === null) {
      message.error("请选择 文章类型！");
    } else if (this.modalData.formFlag === '' || this.modalData.formFlag === null) {
      message.error("请选择 发布形式！");
    } else {
      this.setState({ modalLoading: true });
      save(Object.assign({
        title: this.modalData.title,
        content: this.state.editorState.toHTML(),
        categoryId: this.modalData.categoryId,
        readNum: this.modalData.readNum,
        likeNum: this.modalData.likeNum,
        formFlag: this.modalData.formFlag
      })).then((response: { code: number; data: any; msg: string}) => {
        if (response.code === 0 && response.data) {
          message.success("发布文章成功！");
          // 关闭窗口
          this.setState({ modalVisible: false });
        } else {
          message.error(response.msg);
        }
      }).catch(() => {
        message.error("发布文章失败！");
      }).finally(() => {
        this.setState({ modalLoading: false });
      });
    }
  };

  handleCancel = () => {
    this.setState({ modalVisible: false });
  };

  handleEditorChange = (editorState: string | any) => {
    this.setState({ editorState });
  };

  onTitleChange = (event: any) => {
    // @ts-ignore
    this.modalData.title = event.target.value;
  };

  onCategoryChange = (value: string) => {
    this.modalData.categoryId = value;
  };

  onStateChange = (value: boolean) => {
    this.modalData.formFlag = value ? '0' : '1';
  };

  // 预览
  preview = () => {
    // @ts-ignore
    if (window.previewWindow) {
      // @ts-ignore
      window.previewWindow.close();
    }
    // @ts-ignore
    window.previewWindow = window.open();
    // @ts-ignore
    window.previewWindow.document.write(this.buildPreviewHtml());
    // @ts-ignore
    window.previewWindow.document.close();
  };

  buildPreviewHtml() {
    return `
      <!Doctype html>
      <html>
        <head>
          <title>预览</title>
          <style>
            html,body{
              height: 100%;
              margin: 0;
              padding: 0;
              overflow: auto;
              background-color: #f1f2f3;
            }
            .container{
              box-sizing: border-box;
              width: 1000px;
              max-width: 100%;
              min-height: 100%;
              margin: 0 auto;
              padding: 30px 20px;
              overflow: hidden;
              background-color: #fff;
              border-right: solid 1px #eee;
              border-left: solid 1px #eee;
            }
            .container img,
            .container audio,
            .container video{
              max-width: 100%;
              height: auto;
            }
            .container p{
              white-space: pre-wrap;
              min-height: 1em;
            }
            .container pre{
              padding: 15px;
              background-color: #f1f1f1;
              border-radius: 5px;
            }
            .container blockquote{
              margin: 0;
              padding: 15px;
              background-color: #f1f1f1;
              border-left: 3px solid #d1d1d1;
            }
          </style>
        </head>
        <body>
          <div class="container">${this.state.editorState.toHTML()}</div>
        </body>
      </html>
    `;
  }

  render() {
    const extendControls = [
      {
        key: 'custom-button',
        type: 'component',
        component: (
          <Button
            className="control-item button upload-button"
            data-title="内容预览"
            onClick={this.preview}
          >
            <EyeOutlined />
          </Button>
        ),
      },
    ];

    const layout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    };

    const { editorState, modalVisible, modalLoading } = this.state;
    // @ts-ignore
    return (
      <PageContainer>
        <Row gutter={24}>
          <Col span={3}>
            <Card>
              <Link to="/cms">
                <ArrowLeftOutlined style={{ fontSize: '18px' }} />
                <span style={{ fontSize: '18px' }}> 个人空间</span>
              </Link>

              <Divider />
              <Steps direction="vertical" size="small" current={0}>
                <Step title="写文章" description="This is a description." />
                <Step title="发布文章" description="This is a description." />
                <Step title="审核" description="This is a description." />
                <Step title="审核通过" description="This is a description." />
              </Steps>
            </Card>
          </Col>
          <Col span={21}>
            <Card>
              <Row gutter={24}>
                <Col span={22}>
                  <Input size="large" placeholder="请输入 文章标题" maxLength={100} allowClear onChange={this.onTitleChange}/>
                </Col>
                <Col span={1}>
                  <Button size="large" type="primary" onClick={this.handlePublish}>
                    发布文章
                  </Button>
                </Col>
              </Row>

              <Divider />
              <div className="editor-container">
                <BraftEditor
                  id="editor-with-code-highlighter"
                  value={editorState}
                  // @ts-ignore
                  extendControls={extendControls}
                  onChange={this.handleEditorChange}
                  onSave={this.submitContent}
                />
              </div>
            </Card>
          </Col>
        </Row>

        <Modal
          title="发布文章"
          visible={modalVisible}
          confirmLoading={modalLoading}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          <Form {...layout} layout="horizontal">
            <Form.Item label="文章类型">
              <Select defaultValue={this.modalData.categoryId} onChange={this.onCategoryChange}>
                <Select.Option value="语文">语文</Select.Option>
                <Select.Option value="数学">数学</Select.Option>
                <Select.Option value="英语">英语</Select.Option>
                <Select.Option value="计算机">计算机</Select.Option>
                <Select.Option value="互联网">互联网</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item label="发布形式">
              <Switch checkedChildren="公开" unCheckedChildren="私密" onChange={this.onStateChange} defaultChecked />
            </Form.Item>
          </Form>
        </Modal>
      </PageContainer>
    );
  }
}
